package cn.gene.timeyan.privateletter.webapi.service.impl;

import cn.gene.timeyan.common.exception.TimeyanServiceException;
import cn.gene.timeyan.common.restful.ResponseCode;
import cn.gene.timeyan.pojo.PrivateLetter.NoticeMessage;
import cn.gene.timeyan.pojo.PrivateLetter.PrivateLetter;
import cn.gene.timeyan.pojo.PrivateLetter.Vo.PrivateLetterSenderIdVo;
import cn.gene.timeyan.pojo.ums.vo.UserInfoVo;
import cn.gene.timeyan.privateletter.service.PrivateLetterService;
import cn.gene.timeyan.privateletter.webapi.mapper.PrivateLetterMapper;

import cn.gene.timeyan.ums.service.IUserDetailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@DubboService
@Slf4j
@Service
public class PrivateLetterServicempl implements PrivateLetterService {
    @Autowired
    PrivateLetterMapper mapper;


    @DubboReference
    private IUserDetailService dubboIUserDetailService;

    /**
     *
     * @param senderId 发送者id
     * @param receiverId 接受者id
     * @param content 消息内容
     * @return
     */
    @Override
    public int addPrivateLetter(Long senderId , Long receiverId, String content) {
        PrivateLetter privateLetter = new PrivateLetter();
        privateLetter.setSenderId(senderId);
        privateLetter.setReceiverId(receiverId);
        privateLetter.setContent(content);
        privateLetter.setTopState(0);
        privateLetter.setMessageState(0);
        LocalDateTime now = LocalDateTime.now();
        privateLetter.setCreateTime(now);
        privateLetter.setSendTime(now);
        privateLetter.setUpdateTime(now);
        int row =mapper.insert(privateLetter);
        if (row!= 1){
            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,
                    "添加类别失败，服务器忙（" + ResponseCode.INTERNAL_SERVER_ERROR.getValue() + "），请稍后再次尝试！");

        }
        return row;


    }

    /**
     * 此为新增公告 接收者id强制为0
     * @param title 标题
     * @param content 内容
     * @return
     */
    @Override
    public int addNoticeMessageService(String title, String content) {
        NoticeMessage noticeMessage = new NoticeMessage();
        noticeMessage.setReceiverId(0L);
        noticeMessage.setTitle(title);
        noticeMessage.setContent(content);
        noticeMessage.setMessageState(0);
        LocalDateTime now = LocalDateTime.now();
        noticeMessage.setCreateTime(now);
        noticeMessage.setSendTime(now);
        noticeMessage.setUpdateTime(now);
        int row = mapper.insertNoticeMessage(noticeMessage);

        if (row!= 1){
            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,
                    "添加类别失败，服务器忙（" + ResponseCode.INTERNAL_SERVER_ERROR.getValue() + "），请稍后再次尝试！");

        }
        return row;
    }

    /**
     * 添加通知
     * @param receiverId
     * @param title
     * @param content
     * @return
     */
    @Override
    public int addMessageNotification(Long receiverId, String title, String content) {
        NoticeMessage MessageNotification = new NoticeMessage();
        MessageNotification.setReceiverId(receiverId);
        MessageNotification.setTitle(title);
        MessageNotification.setContent(content);
        MessageNotification.setMessageState(0);
        LocalDateTime now = LocalDateTime.now();
        MessageNotification.setCreateTime(now);
        MessageNotification.setSendTime(now);
        MessageNotification.setUpdateTime(now);
        int row = mapper.insertNoticeMessage(MessageNotification);
        if (row!= 1){
            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,
                    "添加类别失败，服务器忙（" + ResponseCode.INTERNAL_SERVER_ERROR.getValue() + "），请稍后再次尝试！");

        }
        return row;
    }


    /**
     * 删除私信
     * @param privateLetterId
     * @return
     */
    @Override
    public int deleteById(Long privateLetterId) {
        PrivateLetter privateLetter = mapper.getPrivateLetterById(privateLetterId);
//       查询私信是否存在
        if (privateLetter == null){
            throw new TimeyanServiceException(ResponseCode.BAD_REQUEST,
                    "找不到删除的私信（" + ResponseCode.BAD_REQUEST.getValue() + "），请稍后再次尝试！");
        }
        int row = mapper.deleteById(privateLetterId);
        if (row!= 1){
            throw new TimeyanServiceException(ResponseCode.INTERNAL_SERVER_ERROR,
                    "删除失败,服务器忙（" + ResponseCode.INTERNAL_SERVER_ERROR.getValue() + "），请稍后再次尝试！");

        }
        return row;
    }

    /**
     * 得到发送者id
     * @param receiverId
     * @return
     */
    @Transactional
    @Override
    public List<UserInfoVo> getSender(Long receiverId) {
        System.out.println("-------------------------------");
        System.out.println("服务层开始");
        System.out.println("开始获取senderId数字列表类");
        List<PrivateLetterSenderIdVo> senders = mapper.getSenderByReceiverId(receiverId);

        //一个能提取出senderId装进list的算法反正我是看不懂为啥的(             在这里获取senderId
        List<Long> senderIds = senders.stream().map(PrivateLetterSenderIdVo::getSenderId).collect(Collectors.toList());
//遍历剔除重复id
        for  ( int  i  =   0 ; i  <  senderIds.size()  -   1 ; i ++ )  {
            for  ( int  j  =  senderIds.size()  -   1 ; j  >  i; j -- )  {
                if  (senderIds.get(j).equals(senderIds.get(i)))  {
                    senderIds.remove(j);
                }
            }
        }
        System.out.println("senderIds =" +senderIds);

        UserInfoVo userInfoVo ;

        List<UserInfoVo> list = new ArrayList<>();

        //通过id查询到对应的vo类并传到list列表中
        for(Long senderId : senderIds){

            userInfoVo = dubboIUserDetailService.getUserInfoVo(senderId);
            list.add(userInfoVo);
        }
        System.out.println(list);
        System.out.println("服务层结束");

        return list;
    }

    /**
     * 获取历史私信记录
     * @param receiverId
     * @param senderId
     * @return
     */
    @Transactional
    @Override
    public List<PrivateLetter> getContent(Long receiverId, Long senderId) {
        System.out.println("-------------------------------");
        System.out.println("服务层开始");
       return mapper.getContent(receiverId,senderId);

    }

    /**
     *获取所有公告
     * @return 全部公告的list集合
     */
    @Override
    public List<NoticeMessage> getAllNoticeMessageService() {

        return mapper.getAllNoticeMessage(0L);
    }

    /**
     * 获取当前用户的通知
     * @param receiverId 接收者id
     * @return
     */
    @Override
    public List<NoticeMessage> getAllMessageNotificationServiceByReceiverId(Long receiverId) {
        return mapper.getAllNoticeMessage(receiverId);
    }


}
